package com.ruoyi.match.utils;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * Author: 廖振辉
 * Date: 2022/4/7
 * Description:
 */
public class JwtUtils {

    private static final String secretKey = "match";

    // 过期时间一天
    private static final Integer expireTime = 60 * 60 *24;

    // 生成token
    public static String createToken(Integer userId,Map<String,Object> data){
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + expireTime * 1000);
        JwtBuilder builder = Jwts.builder();
        if (data != null){
            builder = builder.setClaims(data);
        }
        JwtBuilder jwtBuilder = builder
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .setId(userId+"");
        return jwtBuilder.compact();
    }

    // 从token中解析出用户id
    public static Integer getUserId(String token){
        int userId;
        try{
            userId = Integer.parseInt(Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getId());
        }catch (ExpiredJwtException exception){
            throw new RuntimeException("token已过期,请重新登录");
        }catch (Exception exception){
            exception.printStackTrace();
            throw exception;
        }
        return userId;
    }

    public static Integer getUserId(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        if (token != null){
            return getUserId(token);
        }
        throw new RuntimeException("用户未登录");
    }

}
